const { escape, execSql } = require('../db/mysql')
const xss = require('xss')

const getList = async (author, keyword) => {
	let sql = `select * from blogs where 1=1 `
	if (author) {
		sql += `and author=${escape(author)} `
	}

	if (keyword) {
		sql += ` and title like %${escape(keyword)}% `
	}

	sql += `order by createtime desc`

	return await execSql(sql)

	/* // 先返回假数据, 但是格式是正确的
	return [
		{
			id: '1',
			title: 'a',
			content: 'a',
			createTime: Date.now(),
			author: 'zhangsan'
		},
		{
			id: '2',
			title: 'b',
			content: 'b',
			createTime: Date.now(),
			author: 'lisi'
		}
	] */
}

const getDetail = async (id) => {
	let sql = `select * from blogs where id=${escape(id)} `
	const rows = await execSql(sql)
	return rows[0]
	/* // 先返回假数据
	return {
		id: '1',
		title: 'a',
		content: 'a',
		createTime: Date.now(),
		author: 'zhangsan'
	} */
}

const newBlog = async (blogData = {}) => {
	// blogData 是一个博客对象, 包含 title content author 属性
	const title = xss(blogData.title)
	const content = xss(blogData.content)
	const author = blogData.author

	const createTime = Date.now()
	const sql = `
		insert into blogs (title, content, createtime, author) values (${escape(
			title
		)}, ${escape(content)}, ${createTime}, ${escape(author)})
	`
	const insertData = await execSql(sql)
	console.log('new blog data....', insertData)
	return {
		id: insertData.insertId
	}
	/* return {
		id: '3' // 表示新建博客, 插入到数据表里面的 id
	} */
}

const updateBlog = async (id, blogData = {}) => {
	// id 就是要更新博客的 id
	// blogData 是一个博客对象, 包含 title content 属性
	const { title, content } = blogData
	const sql = `
		update blogs set title=${escape(title)}, content=${escape(
		content
	)} where id=${escape(id)}
	`

	const result = await execSql(sql)
	console.log('update blog data....', result)
	if (result.affectedRows > 0) {
		return true
	} else {
		return false
	}
}

const delBlog = async (id, author) => {
	// id 就是要删除博客的 id
	const sql = `delete from blogs where id=${escape(id)} and author=${escape(
		author
	)}`
	const result = await execSql(sql)
	console.log('delete blog data....', result)
	if (result.affectedRows > 0) {
		return true
	} else {
		return false
	}
}

module.exports = {
	getList,
	getDetail,
	newBlog,
	updateBlog,
	delBlog
}
